import time
import re
import random
import sys
import hashlib
from uuid import uuid4
from retrying import retry
from requests import request
from urllib.parse import urlencode

"""
appid：yanwei
appSecret：ae681973e0ba812e66cb051b2ddbb587
"""
@retry(stop_max_attempt_number=6, stop_max_delay=3000, wait_fixed=3000, wait_incrementing_increment=500)
def get_key_no(name, flag=None):
    local_time = str(int(time.time()))
    uid = uuid4()
    data1 = {"name": name}
    data = "appid=yanwei&name=%s&time=%s&uuid=%sae681973e0ba812e66cb051b2ddbb587" % (name, local_time, str(uid))
    url = "http://jianshe.facms.cn/api/serve/comp/get-name-by-info"
    md = hashlib.md5(data.encode(encoding="utf-8"))
    header = {
        "appid": "yanwei",
        "uuid": str(uid),
        "time": local_time,
        "sign": md.hexdigest()
    }
    try:
        res = request(method='post', url=url, headers=header, data=data1, timeout=30)
        if flag:
            print(res.json()['data'])
        return res.json()['data']
    except Exception as err:
        if flag:
            print(err)
        return []

@retry(stop_max_attempt_number=6, stop_max_delay=3000, wait_fixed=3000, wait_incrementing_increment=500)
def get_new_key(code, name):
    url = 'http://w.9695.net/comp_md5?company_create=%s&company_code=%s' % (name, code)
    try:
        res = request(method='get', url=url)
        key = res.json()['data']
        return key
    except Exception as err:
        print('获取新keyno err: %s' % err)
        return ''

@retry(stop_max_attempt_number=10, stop_max_delay=3000, wait_fixed=3000, wait_incrementing_increment=500)
def get_gaode_addr(addr_str):
    """
    {'count': '1',
     'geocodes': [{'adcode': '110105',
                   'building': {'name': [], 'type': []},
                   'city': '北京市',
                   'citycode': '010',
                   'country': '中国',
                   'district': '朝阳区',
                   'formatted_address': '北京市朝阳区阜通东大街|6号',
                   'level': '门牌号',
                   'location': '116.483038,39.990633',
                   'neighborhood': {'name': [], 'type': []},
                   'number': '6号',
                   'province': '北京市',
                   'street': '阜通东大街',
                   'township': []}],
     'info': 'OK',
     'infocode': '10000',
     'status': '1'}
    """
    key_list = [
            '7515a833ef27ba7d8c5efcd3f9fc69a8', '9decc56703e0ff54bf3900b1366964b2',
            '424af97f0adbb42d291f7a4ec0a0dbac', '009b3e58ad5ba996be37cd80d9c267ae',
            'ee4c9f14e60cde822ecdea51e70fc04b', '0ab59976e83005aac9f790bb9e364b0f',
            '86e9a4b34c3d907cdd71f5f3f291fda5', '86e9a4b34c3d907cdd71f5f3f291fda5',
            '86e9a4b34c3d907cdd71f5f3f291fda5', 'd4b90a7f0181a20d25f6d450f6452184',
            'd4b90a7f0181a20d25f6d450f6452184', 'd4b90a7f0181a20d25f6d450f6452184',
            'eaed66c971e6264cedfdc0634f890373',
            ]
    addr_str = re.sub(r'[#@*!%]*', '', addr_str)
    url = 'https://restapi.amap.com/v3/geocode/geo?address={}&output=XML&key={}&output=json'.format(addr_str, random.choice(key_list))
    res = request(method='get', url=url, timeout=30)
    res_dict = res.json()
    if res_dict['info'] == 'OK':
        if res_dict['geocodes']:
            return res_dict['geocodes'][0]
        else:
            return {}
    else:
        return {}


if __name__ == '__main__':
    # parms = sys.argv
    # print(parms)
    # get_key_no('山西交科岩土工程有限公司', True)
    # get_key_no('沈阳齐骏建筑装饰工程有限公司', True)
    # get_key_no(parms[1], True)
    #get_gaode_addr('北京市朝阳区阜通东大街6号')
    res = get_gaode_addr('浙江省丽水市农旅休闲观光园建设项目')
    print(res)
    pass


